package com.note.simpleadmin.module.system.service;

import com.note.simpleadmin.entity.BgMenu;
import com.note.simpleadmin.enu.DeleteEnum;
import com.note.simpleadmin.module.system.dao.BgMenuRepository;
import com.note.simpleadmin.module.system.vo.BgMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/***
 *@ClaseName:BgMenuService
 *
 *@Decription:
 *
 *@Author: xubingbing
 *
 *@Date:2019/1/27 0027 18:20
 */
@Service
public class BgMenuService {
    private static final String CACHE_NAME="menu_cache";
    @Autowired
    private BgMenuRepository bgMenuRepository;

    /***
     * 获取菜单树
     * @return
     */
//    @Cacheable(CACHE_NAME)
    public List<BgMenuVo> findAll() {
        List<BgMenu> bglist = bgMenuRepository.findByIsDelete(DeleteEnum.NORMAL.getValue());
        List<BgMenuVo> bgMenuVoList = getChildren("0", BgMenuVo.copy(bglist));
        return bgMenuVoList;
    }
    private List<BgMenuVo> getChildren(String pid, List<BgMenuVo> list) {
        List<BgMenuVo> childrenList = new ArrayList<BgMenuVo>();
        if ("0".equals(pid)) {
            for (BgMenuVo bgMenuVo : list) {
                if (bgMenuVo.getCode().length() == 4) {
                    childrenList.add(bgMenuVo);
                    bgMenuVo.setChildrens(getChildren(bgMenuVo.getCode(), list));
                }
            }
        } else {
            for (BgMenuVo bgMenuVo : list) {
                String code = bgMenuVo.getCode();
                if (bgMenuVo.getCode().substring(0,code.length() - 4).equals(pid)) {
                    //递归获取子节点下的子节点
                    bgMenuVo.setChildrens(getChildren(bgMenuVo.getCode(), list));
                    childrenList.add(bgMenuVo);
                }
            }

        }
        return childrenList;
    }
}
